import { app, BrowserWindow, dialog, ipcMain } from 'electron'
import { readFile, utils } from 'xlsx'

async function createWindow () {
  const win = new BrowserWindow({
    width: 960,
    height: 1280,
    frame: false,
    show: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      webSecurity: false
    } as Any
  })

  win.setMenu(null)

  if (process.argv[2] === 'debug') {
    win.loadURL('http://localhost:8630')
    win.webContents.openDevTools()
    await new Promise(res => setTimeout(res, 500))
  } else {
    win.loadFile('dist/index.html')
  }
  const files = dialog.showOpenDialogSync(win, {
    title: '选择数据文件',
    filters: [{ extensions: ['csv', 'xls', 'xlsx'], name: '*' }],
    properties: ['openFile']
  })
  if (!files?.[0]) {
    win.close()
    return
  }
  let datas = formatData(files[0])
  win.setBounds({
    ...win.getBounds(),
    width: Math.round(Math.max(...datas.map(v => v[0]).flat()) - Math.min(...datas.map(v => v[0]).flat()) + 60),
    height: Math.round(Math.max(...datas.map(v => v[1]).flat()) - Math.min(...datas.map(v => v[1]).flat()) + 90)
  })
  ipcMain.handle('get-xls', (_, force: boolean) => {
    if (force) {
      const files = dialog.showOpenDialogSync(win, {
        title: '选择数据文件',
        filters: [{ extensions: ['csv', 'xls', 'xlsx'], name: '*' }],
        properties: ['openFile']
      })
      if (files?.[0]) {
        datas = formatData(files[0])
      }
    }
    return JSON.stringify(datas)
  })
  win.webContents.reload()

  ipcMain.on('exit', () => {
    win.close()
  })
}

app.whenReady().then(async () => {
  createWindow()
})
app.on('window-all-closed', () => app.exit(0))

function formatData (fPath: string) {
  try {
    const wk = readFile(fPath)
    return utils.sheet_to_json(wk.Sheets[wk.SheetNames[0]], {
      header: 'A'
    }).slice(1).map((v: Any) => {
      const len = Math.sqrt(v.C ** 2 + v.D ** 2)
      return [-v.A, v.B, -v.C, v.D, -v.C / len, v.D / len]
    })
  } catch (e) {
    return []
  }
}
